#include "HistogramPreviewer.h"
#include <QPainter>


HistogramPreviewer::HistogramPreviewer(QWidget *parent)
: QWidget(parent), _maxHistogramVal (0)
{

}



void HistogramPreviewer::paintEvent (QPaintEvent * event)
{
  int width = this->width () - 2;
  int height = this->height () - 2;
  QPainter histogramPainter (this);

  histogramPainter.setBrush (QColor (255, 255, 255));
  histogramPainter.setPen (QColor (0, 0, 0));
  //histogramPainter.fillRect (0, 0, width, height, QColor (255, 255, 255));
  histogramPainter.drawRect (0, 0, width + 1, height + 1);
  histogramPainter.translate (1, 1);


 if (_maxHistogramVal != 0)
  {
    map< QString, HistogramChannel >::iterator iter = _channelMap.begin ();
    
    for (; iter != _channelMap.end (); ++iter)
    {
      if (iter->second.isShow == false)
        continue;
      histogramPainter.setPen (iter->second.color);

      for (int i = 0; i < width; ++i)
      {
        float length = iter->second.histogram[(float)i / width * 256]
                * height / _maxHistogramVal;
        if (length != 0)
          histogramPainter.drawLine (i, height - 1, i, height - length);
      }
    }
  }
}

void HistogramPreviewer::resizeEvent (QResizeEvent * event)
{
  update ();
}

void HistogramPreviewer::_generatePreviewData ()
{
  map< QString, HistogramChannel >::iterator iter = _channelMap.begin ();
  _maxHistogramVal = 0;
  for (; iter != _channelMap.end (); ++iter)
  {
    if (iter->second.isShow == false)
      continue;

    for (int i = 0; i < 256; ++i)
      if (iter->second.histogram[i] > _maxHistogramVal)
        _maxHistogramVal = iter->second.histogram[i];
  }
}

bool HistogramPreviewer::addChannel (const HistogramChannel & channel)
{
  if (!_channelMap.insert (make_pair (channel.channelName, channel)).second)
    return false;
  _generatePreviewData ();
  return true;
}

bool HistogramPreviewer::removeChannel (QString channelName)
{

  map< QString, HistogramChannel >::iterator iter = _channelMap
          .find (channelName);
  if (iter == _channelMap.end ())
    return false;
  _channelMap.erase (iter);
  _generatePreviewData ();
  return true;
}

bool HistogramPreviewer::setChannelShow (QString channelName, bool isShow)
{
  map< QString, HistogramChannel >::iterator iter = _channelMap
          .find (channelName);
  if (iter == _channelMap.end ())
    return false;
  iter->second.isShow = isShow;
  _generatePreviewData ();
  return true;
}

void HistogramPreviewer::clearChannel ()
{
  _channelMap.clear ();
}